using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using XLua;

public class GameMain : MonoBehaviour
{
    LuaEnv luaenv = null;
    
    Action LuaUpdate;
    Action LuaLateUpdate;
    Action LuaFixUpdate;
    void Awake()
    {
        //DontDestroyOnLoad(gameObject);
        


    }

    // IEnumerator Http(){
    //     UnityWebRequest unityWebRequest =     UnityWebRequest.Get("");
    //     yield return unityWebRequest.SendWebRequest();

    //     if(unityWebRequest.result == UnityWebRequest.Result.Success){
    //             unityWebRequest.downloadHandler.text
    //     }
    //     else
    //     {

    //     }
    // }
    // Start is called before the first frame update
    void Start()
    {
        luaenv = new LuaEnv();
        //luaenv.AddBuildin("rapidjson", XLua.LuaDLL.Lua.LoadRapidJson);//加载rapidjson
       
        luaenv.AddLoader(CustomLoader);//自定义加载器 所有的require 都走加载器
        luaenv.DoString("require 'GameMain'");
        Encoding.UTF8.GetBytes("dfdgfdgfdg");
        // Action luaMain= luaenv.Global.Get<Action>("GameStart");
        // luaMain();
        Action<int> luaMain1= luaenv.Global.Get<Action<int>>("GameStart");
        luaMain1(11);
        LuaUpdate = luaenv.Global.Get<Action>("LuaUpdate");
        LuaLateUpdate = luaenv.Global.Get<Action>("LuaLateUpdate");
        LuaFixUpdate = luaenv.Global.Get<Action>("LuaFixUpdate");

       
    }

    byte[] CustomLoader(ref string fileName)
    {
        byte[] result;
        fileName = fileName.Replace(".", "/");
        string luaPath = UtilsCSharp.GetDataPath+"Lua/" + fileName + ".lua";
        Debug.Log(luaPath);
#if UNITY_EDITOR

        string strLuaContent = File.ReadAllText(luaPath);
        result = System.Text.Encoding.UTF8.GetBytes(strLuaContent);
#elif UNITY_ANDROID
        UnityWebRequest request = UnityWebRequest.Get(luaPath);
        request.SendWebRequest();
        while (!request.isDone)
        result = request.downloadHandler.data;
#endif
        Debug.Log(result.Length);
        return result;
    }
    
    void Update()
    {
        LuaUpdate?.Invoke();
        luaenv?.Tick();

    }

    private void LateUpdate()
    {
        LuaLateUpdate?.Invoke();
    }

    private void FixedUpdate()
    {
        LuaFixUpdate?.Invoke();
    }

}
